package top.lyc829.zzl_android.ui.profile.edit_user_info;

import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.xuexiang.constant.TimeConstants;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.grouplist.XUICommonListItemView;
import com.xuexiang.xui.widget.grouplist.XUIGroupListView;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xutil.data.DateUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;
import okhttp3.internal.Util;
import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityEditUserInfoBinding;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.UserInfoBean;
import top.lyc829.zzl_android.logic.util.FormatUtil;
import top.lyc829.zzl_android.logic.util.GlideEngine;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.BaseActivity;

public class EditUserInfoActivity extends BaseActivity {

    private static final int CHOOSE_PHOTO = 1;

    private ActivityEditUserInfoBinding binding;
    private UserInfoBean userInfo;
    private File newAvatar = null;

    XUIGroupListView mGroupListView;
    XUICommonListItemView itemUsername, itemGender, itemPhoneNumber, itemSignature, itemAge, itemBornTime;
    String[] mSexOption = new String[] {"女", "男"};

    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_edit_user_info);
        binding = ActivityEditUserInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 获取上一个页面传来的userInfo
        userInfo = (UserInfoBean) getIntent().getSerializableExtra("userInfo");

        if (userInfo == null) {
            finish();
        }

        mGroupListView = findViewById(R.id.groupListView);

        // 点击返回按钮返回上一页
        binding.mTitleBarEditUserInfo.setLeftClickListener(v -> {
           finish();
        });

        initGroupListView();

        binding.headerImageEdit.setOnClickListener(v -> {
            chooseAvatar();
        });

        binding.btnUpdateUserInfo.setOnClickListener(v -> {
            updateUserInfo();
        });

    }



    /**
     * 从文件系统中选择头像
     */
    private void chooseAvatar() {

        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .isMaxSelectEnabledMask(true)
                .selectionMode(PictureConfig.SINGLE)
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .isEnableCrop(true)
                .showCropFrame(true)
                .showCropGrid(true)
                .hideBottomControls(false)
                .isCompress(true)
                .isAndroidQTransform(true)
                .freeStyleCropEnabled(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        newAvatar = new File(result.get(0).getCompressPath());
                        Glide
                                .with(EditUserInfoActivity.this)
                                .load(result.get(0).getCompressPath())
                                .into(binding.headerImageEdit);
                    }

                    @Override
                    public void onCancel() {
                        // 取消
                    }
                });






    }

//    /**
//     * android 11 选取图片。
//     * 需要权限
//     */
//    private void openAlbumNew() {
//        try {
//            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//            startActivityForResult(intent, CHOOSE_PHOTO);
//        } catch (Exception e) {
//            Utils.Sout(e.getMessage());
//        }
//
//    }

//    /**
//     * android 11以下 选取图片。
//     * 不需要权限
//     */
//    private void openAlbum() {
//        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
//        intent.setType("image/*");
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        startActivityForResult(intent, CHOOSE_PHOTO);
//    }
    

    private void initGroupListView() {

        binding.headerImageEdit.setCircle(true);
        if (!Utils.isStringEmpty(userInfo.getAvatarUrl())) {
            Glide.with(this)
                    .load(userInfo.getAvatarUrl())
                    .into(binding.headerImageEdit);
        }


        itemUsername = mGroupListView.createItemView("昵称");
        itemUsername.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        itemUsername.setDetailText(userInfo.getNickname());

        itemGender = mGroupListView.createItemView("性别");
        itemGender.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        itemGender.setDetailText(Utils.isStringEmpty(userInfo.getGender()) ? "未知" : userInfo.getGender());

//        itemPhoneNumber = mGroupListView.createItemView("手机号");
//        itemPhoneNumber.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
//        itemPhoneNumber.setDetailText(userInfo.getAccount());

        itemSignature = mGroupListView.createItemView("简介");
        itemSignature.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        itemSignature.setDetailText(userInfo.getSignature());

        itemAge = mGroupListView.createItemView("年龄");
        itemAge.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        itemAge.setDetailText(userInfo.getAge() == null ? "" : userInfo.getAge().toString());

        itemBornTime= mGroupListView.createItemView("出生日期");
        itemBornTime.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        itemBornTime.setDetailText(
                Utils.isStringEmpty(userInfo.getBornTime()) ? "" : DateUtils.millis2String(Long.parseLong(userInfo.getBornTime()), DateUtils.yyyyMMdd.get()));


        View.OnClickListener onClickListener = v -> {
            if (v instanceof XUICommonListItemView) {
                String text = (String) ((XUICommonListItemView) v).getText();

                switch (text) {
                    case "昵称":
                        changeUsername();
                        break;
                    case "性别":
                        changeGender();
                        break;
//                    case "手机号":
//                        changePhoneNumber();
//                        break;
                    case "简介":
                        changeSignature();
                        break;
                    case "出生日期":
                        changeBornTime();
                    default:
                        break;

                }
            }
        };

        int size = DensityUtils.dp2px(this, 20);
        XUIGroupListView.newSection(this)
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(itemUsername, onClickListener)
                .addItemView(itemGender, onClickListener)
                .addItemView(itemSignature, onClickListener)
                .addItemView(itemBornTime, onClickListener)
                .addTo(mGroupListView);
    }

    /**
     * 修改出生日期
     */
    private void changeBornTime() {
        new TimePickerBuilder(this, (date, v) -> {
            userInfo.setBornTime(String.valueOf(DateUtils.date2Millis(date)));
            itemBornTime.setDetailText(DateUtils.date2String(date, DateUtils.yyyyMMdd.get()));
        })
                .setTitleText("出生日期")
                .build()
                .show();
    }

    /**
     * 修改简介
     */
    private void changeSignature() {
        new MaterialDialog.Builder(this)
                .title("修改简介")
                .input(
                        "请输入简介",
                        "",
                        false,
                        ((dialog, input) -> {}))
                .inputRange(1, 250)
                .positiveText("确定")
                .negativeText("取消")
                .onPositive((dialog, which) -> {
                    userInfo.setSignature(dialog.getInputEditText().getText().toString());
                    itemSignature.setDetailText(userInfo.getSignature());

                })
                .cancelable(false)
                .show();
    }


    private void changeUsername() {
        new MaterialDialog.Builder(this)
                .title("修改昵称")
                .input(
                        "请输入昵称",
                        "",
                        false,
                        ((dialog, input) -> {}))
                .inputRange(3, 10)
                .positiveText("确定")
                .negativeText("取消")
                .onPositive((dialog, which) -> {
                    if (FormatUtil.isSpecialCharacters(dialog.getInputEditText().getText().toString().trim())) {
                        Utils.showToast("昵称不能包含特殊字符");
                        return;
                    }
                    userInfo.setNickname(dialog.getInputEditText().getText().toString().trim());
                    itemUsername.setDetailText(userInfo.getNickname());
                })
                .cancelable(false)
                .show();
    }

    /**
     * 选择性别
     * XUI组件
     */
    private void changeGender() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (v, options1, options2, options3) -> {
            userInfo.setGender(mSexOption[options1]);
            itemGender.setDetailText(userInfo.getGender());
            return false;
        })
                .setTitleText("性别选择")
                .setSelectOptions((userInfo.getGender() == null || userInfo.getGender().equals("女")) ? 0 : 1)
                .build();
        pvOptions.setPicker(mSexOption);
        pvOptions.show();
    }

//    private void changePhoneNumber() {
//        new MaterialDialog.Builder(this)
//                .title("修改手机号")
//                .inputType(InputType.TYPE_CLASS_PHONE)
//                .input(
//                        "请输入手机号",
//                        "",
//                        false,
//                        ((dialog, input) -> {}))
//                .inputRange(11, 11)
//                .positiveText("确定")
//                .negativeText("取消")
//                .onPositive((dialog, which) -> {
//                    userInfo.setAccount(dialog.getInputEditText().getText().toString());
//                    itemPhoneNumber.setDetailText(userInfo.getAccount());
//
//                })
//                .cancelable(false)
//                .show();
//
//    }


    private void updateUserInfo() {

        if (Utils.isStringEmpty(userInfo.getNickname())) {
            Utils.showToast("昵称不能为空");
            return;
        }

        if (Utils.isStringEmpty(userInfo.getGender())) {
            Utils.showToast("请选择性别");
            return;
        }
        if (Utils.isStringEmpty(userInfo.getSignature())) {
            Utils.showToast("简介不能为空");
            return;
        }
        if (Utils.isStringEmpty(userInfo.getBornTime())) {
            Utils.showToast("出生日期不能为空");
            return;
        }




        String body = new Gson().toJson(userInfo);

        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("user_id", userInfo.getId().toString());
        bodyMap.put("signature", userInfo.getSignature());
        bodyMap.put("nickname", userInfo.getNickname());
        bodyMap.put("gender", userInfo.getGender());
        bodyMap .put("born_time",userInfo.getBornTime());
        bodyMap .put("age","10");

        List<Pair<String, File>> list = null;
        if (newAvatar != null) {
            list = new ArrayList<>();
            list.add(new Pair<>("avatar", newAvatar));
        }

        HttpUtil httpUtil = HttpUtil.getInstance(MyApp.getContext());
        httpUtil.sendMultipart(Url.UPDATE_USER_INFO, bodyMap, list, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resultStr = res.body().string();
                Utils.Sout(resultStr);
                ResultBean<List<Void>> resultBean = JsonUtilNew.fromJsonArray(resultStr, Void.class);
                if (resultBean.getCode().equals(200)) {
                    handler.post(() -> showSuccessDialog());
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.showToastSync("失败");
            }
        });


        // TODO: 这里json转map时整形会变成浮点型，Gson的问题
//        HashMap<String, Object> body = gson.fromJson(gson.toJson(userInfo), HashMap.class);

    }

//    /**
//     * 上传用户头像
//     */
//    private void uploadUserAvatar() {
//        if (newAvatar == null) {
//            showSuccessDialog();
//        } else {
//            HttpUtil httpUtil = HttpUtil.getInstance(MyApp.getContext());
//            httpUtil.uploadPhoto(Url.UPDATE_USER_INFO, newAvatar, new HttpUtil.MyCallback() {
//                @Override
//                public void success(Response res) throws IOException {
//                    String resultStr = res.body().string();
//                    ResultBean<Void> resultBean = JsonUtilNew.fromJsonObject(resultStr, Void.class);
//                    if (resultBean.getCode().equals(200)) {
////                        uploadUserAvatar();
//                        handler.post(() -> {
//                            // 修改成功后显示Dialog
//                            showSuccessDialog();
//                        });
//                    }
//
//                }
//
//                @Override
//                public void failed(IOException e) {
//                    Utils.showToastSync("失败");
//                }
//            });
//        }
//
//    }

    private void showSuccessDialog() {
        new MaterialDialog.Builder(this)
                .title("成功")
                .content("修改成功")
                .positiveText("确定")
                .onPositive((dialog, which) -> finish())
                .show();
    }




}